有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java自动遍历为组件值动态创建的JPanel

我有一个程序,根据用户定义的程序开始时的选择创建动态数量的JPanel和组件。已经说过,每个jpanel和组件都是通过一个循环创建的,使它们都相同,然后它们被放入一个列表(jpanel被放入一个列表)

话虽如此,我已经能够得到jpanel,然后抓取组件并使用系统显示它们。出来但它们位于组件对象中。如何获取组件的值?还是我做错了

基本上,我正在尝试让基于用户定义的tabs/jpanel自动生成,这是可行的。然后用户填写一些信息并点击“Generate”,在这里我需要遍历tabs/jpanels/components并将它们放入正确的对象中

下面是我的程序的一个工作示例,简化了for,选项卡的类型更少(我只允许创建AP选项卡),对象类的选项更少:

有两个对象类APObject正在扩展泛型对象。MVCE是主程序的开始,它会向您询问一些用户定义的问题,这些问题会生成选项卡/面板。然后是信息收集。java到数据收集,它在其中创建选项卡和面板。GenerateActionPerformed(ActionEvent evt)方法是我试图从面板组件中获取信息,并将它们放入APObject或它们需要进入的任何对象中

MVCE:

    public class MVCE extends javax.swing.JFrame {
        int numGenerate[];
        private javax.swing.JComboBox cb;
        /**
         * Creates new form MVCE
         */
        public MVCE() {
            this.numGenerate = new int[3];
            initComponents();
        }

        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {

            jComboBox1 = new javax.swing.JComboBox();
            jComboBox2 = new javax.swing.JComboBox();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5" }));
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jComboBox1ActionPerformed(evt);
                }
            });

            jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5" }));
            jComboBox2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jComboBox2ActionPerformed(evt);
                }
            });

            jLabel1.setText("How many switches?");

            jLabel2.setText("APS");

            jButton1.setText("Create Button");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(jButton1))
                    .addContainerGap(264, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(15, 15, 15)
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton1)
                    .addContainerGap(140, Short.MAX_VALUE))
            );

            jLabel1.getAccessibleContext().setAccessibleName("How many switches");

            pack();
        }// </editor-fold>                        

        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:
           this.setVisible(false);
           InfoGathering Info = new InfoGathering(numGenerate);
        }                                        

        private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {                                           
            // TODO add your handling code here:
            cb = (javax.swing.JComboBox)evt.getSource();
            String APNumber = (String)cb.getSelectedItem();
            //System.out.println(APNumber + "AP Number");
            numGenerate[1] = Integer.valueOf(APNumber);
        }                                          

        private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
            // TODO add your handling code here:
            cb = (javax.swing.JComboBox)evt.getSource();
            String APNumber = (String)cb.getSelectedItem();
            //System.out.println(APNumber + "AP Number");
            numGenerate[0] = Integer.valueOf(APNumber);
        }                                          

        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(MVCE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(MVCE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(MVCE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(MVCE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>

            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MVCE().setVisible(true);
                }
            });
        }

        // Variables declaration - do not modify                     
        private javax.swing.JButton jButton1;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JComboBox jComboBox2;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        // End of variables declaration                   
    }

INFOGATHERING:
public class InfoGathering {
   //public int infoVariables[];
   public InfoGathering(int[] infoVars) {
    startInfo(infoVars);
    } 

   private void startInfo(int[] infoVars) {
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DataGathering(infoVars).setVisible(true);


            }
        });
    }

   //End of clss below
}

DATAGATHERING:
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author kmalik
 */
public class DataGathering extends javax.swing.JFrame {
private int infoVariables[];
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel OuterPane;
    //SwitchObject SWOb[] = new SwitchObject[30];
    //APObject APOb[] = new APObject[30];
    //ControllerObject CoOb[] = new ControllerObject[1];
    //int devicesArrayCountSW = 0;
    //int devicesArrayCountAP = 0;
    //int devicesArrayCountCO = 0;



    /**
     * Creates new form DataGathering
     * @param intVars
     */
    public DataGathering(int[] intVars) {
        infoVariables = Arrays.copyOf(intVars, intVars.length);
        initComponents();
        initDynamic();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridLayout(1, 0));

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    private void initDynamic() {
        OuterPane = new javax.swing.JPanel();
        getContentPane().add(OuterPane);
        OuterPane.add(jTabbedPane1);
        JButton GenerateCode = new JButton("Generate Code");
        OuterPane.setLayout(new BoxLayout(OuterPane, BoxLayout.Y_AXIS));
        OuterPane.add(GenerateCode);

        GenerateCode.addActionListener(new java.awt.event.ActionListener() {
            private APObject Aobj;
            private JPanel jobj;
            private Component Components[];
            private Component components;
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                GenerateActionPerformed(evt);
            }

            private void GenerateActionPerformed(ActionEvent evt) {  
               //To change body of generated methods, choose Tools | Templates.
                for(int i = 0; apList.size() > i; i++) {
                    //jobj = (JPanel) jList.get(i);
                    //System.out.println(jobj
                    Aobj = apList.get(i);
                    jobj = jList.get(i);
                    Components = jobj.getComponents();
                    System.out.println(Components + " Componenets of first panel");
                    for (int a=0; a < Components.length; a++) {
                        components = jobj.getComponent(a);
                        System.out.println(components);
                        if (Components[a] instanceof JComboBox) {

                        }
                    }
                }
            }

        });
        int SwitchCount = 1 , APCount = 1,CoCount = 1;
        //String jp;
        //need public# of switches, APs and controllers

        for(int devicesCount =0;devicesCount < infoVariables.length;devicesCount++) {
            if (devicesCount == 2 && infoVariables[devicesCount] == 1) {
                createTab(CoCount, devicesCount);
            }
            for(int b=0; b < infoVariables[devicesCount]; b++) {
             if (devicesCount == 0) {
                //SWITCHES DYNAMICALLY CREATE
                createTab(SwitchCount,devicesCount);
                SwitchCount++;
             } else if (devicesCount==1) {
                //AP DYNAMICALLY CREATE
                 createTab(APCount,devicesCount);
                 APCount++;
             } //end of full if loop         
            } //end of for loop
        } // end of outer for loop
    }                     
    private javax.swing.JTabbedPane jTabbedPane1;




   //ArrayList<SwitchObject> swList = new ArrayList<>();
    ArrayList<APObject> apList = new ArrayList<>();
    //ArrayList<ControllerObject> coList = new ArrayList<>();
    ArrayList<JPanel> jList = new ArrayList<>();
    private void createTab(int z,int y) {
        if (y==0) {
           //CREATE SWITCH TAB/PANEL


        } else if (y==1) {
           JPanel jp = new JPanel();
           jTabbedPane1.addTab("AP_"+z,jp);
           jp.setName("AP"+z);
           APObject APOb = new APObject(jp.getName(), z);
           apList.add(APOb);
           jList.add(jp);

           setLayout(new FlowLayout());

           //Add Type of Device Checkbox
           String[] apListName = {"APExample1","APExample2"};
           JComboBox apListChkBox = new JComboBox(apListName);
           jp.add(apListChkBox);

           //Add NasID of Device with Label
           JLabel apnasIDLabel = new JLabel("AP ID");
           String apnasID;
           JTextField apnasIDComboBox = new JTextField();
           apnasIDComboBox.setColumns(9);
           jp.add(apnasIDLabel);
           jp.add(apnasIDComboBox);

           //SNMP Location
           JLabel apLocLabel = new JLabel("Location");
           String apLoc;
           JTextField apLocComboBox = new JTextField();
           apLocComboBox.setColumns(9);
           jp.add(apLocLabel);
           jp.add(apLocComboBox);

           jp.setBorder(BorderFactory.createLineBorder(Color.black));
           this.pack();

        } else if (y == 2) {
           //CREATE CONTROLLER TAB/PANEL
        }
    }
}

APOBJECT:
public class APObject extends GenericObject {
    private int channelScheme;


    APObject(String x, int y) {
        super(x,y);
    }

    //ip scheme box/subnet box get/set

    //location get/set

    //channel scheme get/set

    private void setChannelScheme(int x) {
        channelScheme = x;
    }

    private int getChannelScheme() {
        return channelScheme;
    }

}

GENERICOBJECT:
public class GenericObject {
    private int telephone;
    private String ipScheme;
    private String Location;
    public String DName;


    public int getTelephone() {
        return telephone;
    }

    protected void setTelephone(int x) {
        telephone = x;
    }

    protected String getipScheme() {
        return ipScheme;
    }

    protected void setipScheme(String x) {
        ipScheme = x;
    }

    protected String getLocation() {
        return Location;
    }

    protected void setLocation(String x) {
        Location = x;
    }

    public GenericObject (String SName, int Tab) {
        DName = SName;
        int TabNum = Tab;
    }


}

共 (0) 个答案